<!DOCTYPE html>
<html>
    <head>
        <meta content="text/html;" charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>一起来摇歌！</title>
        <style>
            .playing {
                background-color: #777;
                color: #eee;
            }
        </style>
    </head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/core.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/md5.js"></script>
    <style>
        .center{
            display: table;
            margin: 0 auto;
        }
        .container {
          position: relative;
        }
        .vertical-center {
          margin: 0;
          position: absolute;
          top: 50%;
          -ms-transform: translateY(-50%);
          transform: translateY(-50%);
        }
        </style>
    <body style="background-color: #556; color: #aaa; margin: 0; overflow-x:hidden;">
        <div style="top:0; left: 0; height: 158px; width: 100vw; position: sticky; overflow: hidden;background: rgba(68, 68, 85, 0.8);">
            <div class="center" style=" width: auto;">
                <div style="display: flex; margin-top: 4px;">
                    <span style="vertical-align: middle;" onclick="getSongsRandom()">
                        <h1 style="color: rgb(161, 193, 255); ">一起来摇歌！</h1>
                    </span>
                    <div class="container">
                        <div class="vertical-center">
                            <div style="vertical-align: middle;">
                                <div style="display: flex;">
                                    <button onclick="searchSongs()" style="font-size:16px; width: 65px;
                                    background-color:#777; color: #ddd;">搜歌：</button>
                                    <input type="text" name="stext" id="stext" 
                                    style="background-color:#555; color: #eee; width: 60px; margin-left: 4px;">
                                </div>
                                <div style="display: flex; color: #ddd; margin-top: 8px;">
                                    单曲循环
                                    <input type="checkbox" id="alongwith" onclick="toggleAlongwith()">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <audio controls></audio>
            </div>
        </div>
        <div id="servinfo" class="center" style="margin-top: 8px; width: auto; padding-left: 3px; padding-right: 3px;">
            <div style="font-size: small;">
                输入Navidrome服务器地址和登录信息，点击“<font color="#A1C1FF">一起来摇歌！</font>”。<br/>
                兼容 Subsonic API 的服务器都可以。<br/><br/>
                安装版不支持无签名的 https 服务器。<br/>
                如果服务器地址是 https 但是又没有签名的，<br/>
                请访问网页版的<a href="https://tools.gxglhyy.top/rsongs.html"><font color="#A1C1FF">一起来摇歌！</font></a><br/>
                在输入地址后点击“测试服务器”在新页面中打开服务器地址，<br/>
                最后再回来点击“<font color="#A1C1FF">一起来摇歌！</font>”。
            </div>
            <div style="margin-top: 12px;">
                服务器地址：
            </div>
            <input type="text" name="baseurl" id="baseurl" oninput="setTestSeverHref()" style="background-color:#555;color: #aaa;">
            <a id="testserver" style="margin-left: 5px;color: #aaa;" target="_blank" >测试服务器</a>
            <div style="margin-top: 8px;">
                用户名：
            </div>
            <input type="text" name="uname" id="uname" style="background-color:#555;color: #aaa;">
            <div style="margin-top: 8px;">
                密码：
            </div>
            <input type="password" name="pwd" id="pwd" style="background-color:#555;color: #aaa;">
        </div>
        <div id="output" class="center" style="box-sizing: border-box; margin-top: 8px; padding-left: 3px; padding-right: 3px;">    
            <div style="box-sizing: border-box; border: 1px solid #777; padding: 5px;">
                <b>播放列表：</b>
                <div id="plcontainer" ></div>
                <div id="ad" style="width: 100%;">
                </div>
            </div>
            <div id="lyrics" style="box-sizing: border-box; margin-top: 10px; border: 1px solid #777; padding: 5px;">歌词：
            </div>
        </div>
    </body>
    <script>
        // const { appWindow } = window.__TAURI__.window
        // appWindow.maximize();

        document.querySelector('#output').style.width = `${document.querySelector('#servinfo').offsetWidth - 4}px`

        let CURRENT_SONGS = []

        if (localStorage.getItem('paras')) {
            let baseurl = document.querySelector('#baseurl')
            baseurl.value = JSON.parse(localStorage.getItem('paras')).b
            setTestSeverHref()
        }

        function setTestSeverHref() {
            let testserver = document.querySelector('#testserver')
            testserver.href = document.querySelector('#baseurl').value
        }
        function getSongsRandom() {
            let url = `${getURL('getRandomSongs')}&size=13`
            console.log(`getSongsRandom: ${url}`)
            fetch(url)
            .then(d => {
                return d.json()
            })
            .then(j =>{
                CURRENT_SONGS = j["subsonic-response"]["randomSongs"]['song']
                createPlayList(CURRENT_SONGS)
                play(0)
            })
            getAd()
        }

        function searchSongs() {
            let stext = document.querySelector('#stext').value
            let url = `${getURL('search2')}&query=${stext}&songCount=13`
            console.log(`searchSongs: ${url}`)
            fetch(url)
            .then(d => {
                return d.json()
            })
            .then(j =>{
                CURRENT_SONGS = j["subsonic-response"]["searchResult2"]['song']
                createPlayList(CURRENT_SONGS)
                play(0)
            })
            getAd()
        }

        function getAd() {
            let ad = document.querySelector('#ad')
            const url = 'https://ad.gxglhyy.top/rest/getAd?c=rmsong&v=0.0.1'
            fetch(url)
            .then(d => { return d.json() })
            .catch(e => {
                ad.innerHTML = '<h2><a href="https://gxglhyy.top/cppeasyx/" target="_blank" style="color: #aaa;">广告展位</a></h2>'
            })
        }

        function createPlayList(songs) {
            let ul = document.createElement('div')
                ul.id = 'playlist'
                CURRENT_SONGS.forEach((song, index) => {
                    let li = document.createElement('div')
                    li.textContent = song.artist + ": " + song.title
                    li.id = song.id
                    li.contentType = song.contentType
                    li.index = index
                    li.addEventListener('dblclick', playClicked)
                    ul.appendChild(li)
                })

                let oEl = document.querySelector('#plcontainer')
                document.querySelector('#playlist') === null ? 0 : oEl.removeChild(document.querySelector('#playlist'))
                oEl.appendChild(ul)
                /*
                let ad = document.querySelector("#ad")
                oEl.removeChild(ad)
                oEl.appendChild(ad)
                */
        }

        function play(index) {
            console.log(CURRENT_SONGS[index])

            let audio = document.querySelector('audio')

            if (parseInt(audio.getAttribute('indexid')) === CURRENT_SONGS[index].id) {
                audio.play()
                return
            }

            let playlist = document.querySelectorAll('#playlist div')
            playlist.forEach((l, pin) => {
                pin === index ? l.classList.add('playing') : l.classList.remove('playing')
            });

            getSongLyrics(CURRENT_SONGS[index])

            let url = `${getURL('download')}&id=${CURRENT_SONGS[index].id}`
            console.log(`download: ${url}`)
            
            audio.setAttribute('src', url)
            audio.setAttribute('indexid', CURRENT_SONGS[index].id)
            audio.setAttribute('index', index)
            audio.load()
            audio.play()
            const nextIdex = (document.querySelector('#alongwith').checked ? index : index + 1) % playlist.length
            audio.onended =  (e =>  play(nextIdex))
        }

        function toggleAlongwith() {
            let playlist = document.querySelectorAll('#playlist div')
            if (playlist.length > 0) {
                let audio = document.querySelector('audio')
                index = parseInt(audio.getAttribute('index'))
                const nextIdex = (document.querySelector('#alongwith').checked ? index : index + 1) 
                    % playlist.length
                audio.onended =  (e =>  play(nextIdex))
            }
        }

        function playClicked(e) {
            play(parseInt(e.target.index))
        }

        function getURL(MName) {
            let SALT = 'fe28@^~fei'
            let paras = {
                    b: document.querySelector('#baseurl').value,
                    u: document.querySelector('#uname').value,
                    s: SALT,
                    // p: document.querySelector('#pwd').value,
                    t:  CryptoJS.MD5(document.querySelector('#pwd').value+SALT).toString(),
                    date: Date()
                }
            if (localStorage.getItem('paras') && document.querySelector('#uname').value === '') {
                // todo: 判断时间与SALT是否变更。
                paras = JSON.parse(localStorage.getItem('paras'))
            }
            console.log(paras)
            localStorage.setItem('paras', JSON.stringify(paras))
            return `${paras.b}/rest/${MName}?f=json&c=rmsongs&v=1.16.1&u=${paras.u}&t=${paras.t}&s=${paras.s}`
        }

        function getSongLyrics(song) {
            
            let lyrics = document.querySelector('#lyrics')
            document.querySelectorAll('#lyrics div').forEach(c => lyrics.removeChild(c))

            const url = `${getURL('getLyrics')}&artist=${encodeURIComponent(song.artist)}&title=${encodeURIComponent(song.title)}`
            console.log(`getLyris: ${url}`)

            fetch(url)
            .then(d => {
                return  d.json()
            })
            .then(j => {
                let lyricsValues =  j["subsonic-response"]["lyrics"]["value"]
                if (lyricsValues === '' || lyricsValues === '暂无歌词') {
                    fetch(`https://lrclib.net/api/search?q=${encodeURIComponent(song.title+'-'+song.artist)}`)
                    .then(d => {return d.json()})
                    .then(l => {
                        lyricsValues = l[0]["plainLyrics"]
                        console.log(`LRCLib Completed: https://lrclib.net/api/search?q=${encodeURIComponent(song.title+'-'+song.artist)}`)
                        createLyricsDiv(lyricsValues)
                    })
                    .catch(e => {
                        console.log(`LRCLib Error: https://lrclib.net/api/search?q=${encodeURIComponent(song.title+'-'+song.artist)}`)
                    })
                } else {
                    console.log(`getLyris Completed: ${url}`)
                    createLyricsDiv(lyricsValues)
                }
                
            })
            function createLyricsDiv(lyricsValues) {
                let str = ''
                lyricsValues.split('\n').forEach((l, index) => {
                    if (index % 4 < 3) {
                        str += l + '  '
                    } else {
                        str += l
                        let div = document.createElement('div')
                        div.textContent = str
                        lyrics.appendChild(div)
                        str = ''
                    }
                    
                })
            }
        }

    </script>
</html>